#include "StdAfx.h"
#include "rtfinternet.h"
#include "Wininet.h"
#include <mmsystem.h>

RtfInternet::RtfInternet(void)
{
	m_hOpen = NULL;
	m_hConnect = NULL;
	memset(m_strAgent,0,64) ;
}

RtfInternet::~RtfInternet(void)
{
	if (m_hOpen != NULL) InternetCloseHandle(m_hOpen);
}

BOOL RtfInternet::Open()
{
	if (m_hOpen != NULL) InternetCloseHandle(m_hOpen);

	DWORD dwFlags;
	InternetGetConnectedState(&dwFlags, 0);
	CHAR strAgent[64];
	sprintf(m_strAgent, "Agent%ld", timeGetTime());
//	sprintf(m_strAgent, "Agent");
	if(!(dwFlags & INTERNET_CONNECTION_PROXY))
		m_hOpen = InternetOpenA(strAgent, INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0);
	else
		m_hOpen = InternetOpenA(strAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

	if(!m_hOpen)
	{
		AfxMessageBox("Internet Connection Error!");
		return FALSE;
	}
	return TRUE;
}

void RtfInternet::Close()
{
	if (m_hOpen != NULL) InternetCloseHandle(m_hOpen);
	m_hOpen = NULL;
}

int RtfInternet::SendUrl(const CString& strUrl,CString& strGet)
{
	strGet = "";

	DWORD dwSize;
	CHAR   szHead[] = "Accept: */*\r\n\r\n";
	char szTemp[16384];

	if ( !(m_hConnect = InternetOpenUrlA ( m_hOpen, strUrl, szHead,
		lstrlenA (szHead), INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD |INTERNET_FLAG_NO_AUTO_REDIRECT, 0)))
	{  
	TRACE("\nCannot OPen URL!\n"+strUrl);
	return -1;
	}


	DWORD dwByteToRead = 0;
	DWORD dwSizeOfRq = 4;
	DWORD dwBytes = 0;
	char Buff[10];

	if (!HttpQueryInfo(m_hConnect, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, 
		(LPVOID)&dwByteToRead, &dwSizeOfRq, NULL))
	{
		dwByteToRead = 0;
	}
	if (!HttpQueryInfo(m_hConnect, HTTP_QUERY_STATUS_CODE, 
                  (LPVOID)Buff, &dwSizeOfRq, NULL))
	{
		dwByteToRead = 0;
		return -1;
	}
	else if(atoi(Buff) >=300)
	{
		dwByteToRead = 0;
		return -1;
	}


	DWORD start;
	DWORD end;
	DWORD time;
	CString tempstring;
	time = 10;
	start = timeGetTime();
	do
	{
		if (!InternetReadFile (m_hConnect, szTemp, 16384,  &dwSize))
		{
			TRACE("\nRead File Error!");
			return -1;
		}
		if (dwSize==0)
			break;
		else {
			szTemp[dwSize] = '\0';
			strGet+=szTemp;
		}
		dwBytes+=dwSize;
		if(dwByteToRead)
		{
			tempstring.Format("%d%%",(dwBytes*100)/dwByteToRead);
			//SetDlgItemText(IDC_PERCENT_TEXT,tempstring);
		}
		FLOAT fSpeed = 0;
		fSpeed = (float)dwBytes;
		fSpeed /= ((float)time)/1000.0f;
		fSpeed /= 1024.0f;
		tempstring.Format("%dKB/s",fSpeed);
		//		SetDlgItemText(IDC_SPEED_TEXT,tempstring);
		end = timeGetTime();
		time = end - start;
		if(time == 0)
			time = 10;
	}while (TRUE);

	return 1;

}
